<?php

namespace app\common\model;

use support\Request;
use think\Db;
use think\Model;
use think\Request as ThinkRequest;

class Member extends Model
{

    public $page_info;

    // 字典查询
    public function dictGet($key = 'member_name', $value = 'member_name') {
        $keyword = \Think\Request::instance()->param('keyword', '', 'trim');
        $map = [];
        $keyword and $map['member_name'] = ['like', '%'.$keyword.'%'];

        $list = Db::name('member')->where($map)->order('member_id desc')->limit(0, 10)->select();

        $result = [];
        foreach ($list as $item) {
            $result[$item[$key]] = $item[$value];
        }

        return $result;
    }

    // 字典查询
    public function dictNameMobileGet($key = 'member_id') {
        $keyword = \Think\Request::instance()->param('keyword', '', 'trim');
        $map = [];
        $mapor = [];
        $keyword and $map['member_name'] = ['like', '%'.$keyword.'%'];
        $keyword and $mapor['member_mobile'] = ['like', '%'.$keyword.'%'];

        $list = Db::name('member')->where($map)->whereOr($mapor)->order('member_name desc')->limit(0, 10)->select();

        $result = [];
        foreach ($list as $item) {
            $result[$item[$key]] = $item['member_name'] . '|' . $item['member_mobile'];
        }

        return $result;
    }

    // erp 登录
    public function erpLogin($params) {
        try {
            Db::startTrans();
            $erp_member_info = Request::erpLogin($params);

            // 查询用户是否存在
            $member_info = $this->getMemberInfo(['member_erpid' => $erp_member_info['number']]);
            if(!$member_info) {
                // 注册
                $member = array();
                $member['member_password'] = md5($params['pwd']);
                $member['member_email'] = '';
                $member['member_mobile'] = $erp_member_info['phone'];
                $member['member_avatar'] = $erp_member_info['headimgurl'];
                $member['member_truename'] = $erp_member_info['name'];
                $member['member_name'] = $erp_member_info['user'];
                $member['member_type'] = $erp_member_info['type'];
                $member_id = $this->addMember($member);

                $member_info = $this->getMemberInfoByID($member_id);

                $this->createErpInviter($member_info, $erp_member_info);
            } else {
                // 更新用户信息
                $member = array();
                $member['member_password'] = md5($params['pwd']);
                $member['member_mobile'] = $erp_member_info['phone'];
                $member_info['member_avatar'] or $member['member_avatar'] = $erp_member_info['headimgurl'];
//                $member_info['member_truename'] or $member['member_truename'] = $erp_member_info['name'];
                $member['member_name'] = $erp_member_info['user'];
                $member['member_type'] = $erp_member_info['type'];
                $this->editMember(['member_id' => $member_info['member_id']], $member);
            }

            // 数据更新
            $this->editMember([
                'member_id' => $member_info['member_id']
            ], [
                'member_erpid' => $erp_member_info['number'],
                'member_erpinfo' => json_encode($erp_member_info, JSON_UNESCAPED_UNICODE),
                'member_logintime' => time(),
                'member_old_logintime' => $member_info['member_logintime'],
                'member_login_ip'   => \think\Request::instance()->ip(),
                'member_old_login_ip' => $member_info['member_login_ip'],
            ]);

            $member_info = $this->getMemberInfo(['member_erpid' => $erp_member_info['number']]);

            // 更新用户层级关系
            $this->updateMemberInviter($member_info);
            Db::commit();
            return $member_info;
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }

    // 更新用户层级关系
    public function updateMemberInviter($member_info) {
        $result = Request::erpUserRelation($member_info);
        $inviter_model = new Inviter();

        $member_id = $member_info['member_id'];
        if(!empty($result['core_number'])) {
            // 核心用户检测
            $member_info = $this->getMemberInfo(['member_erpid' => $result['core_number']]);
            if(!$member_info) {
                // 不存在则加入系统
                $member = array();
                $member['member_erpid'] = $result['core_number'];
                $member['member_password'] = md5(mt_rand());
                $member['member_mobile'] = $result['core_phone'];
                $member['member_name'] = $result['core_name'];
                $member['member_type'] = MEMBER_TYPE_2;
                $core_member_id = $this->addMember($member);
                $member_info = $this->getMemberInfo(['member_id' => $core_member_id]);

                $this->createErpInviter($member_info, [
                    'name' => $result['core_name'],
                    'type' => $member['member_type'],
                    'phone' => $result['core_phone'],
                ]);
            } else {
                // 存在则更新层级关系
                $core_member_id = $member_info['member_id'];
            }

            // 更新上级
            $this->editMember(['member_id' => $member_id], [
                'inviter_id' => $core_member_id,
            ]);

            if($member_info['member_type'] != MEMBER_TYPE_2) {
                // 更新等级
                $inviter_model->editInviter(['inviter_id' => $core_member_id], [
                    'inviter_type' => MEMBER_TYPE_2
                ]);
                $member_info = $this->getMemberInfo(['member_id' => $core_member_id]);
            }

            $member_id = $member_info['member_id'];
        }

        if(!empty($result['dir_number'])) {
            // 核心用户检测
            $member_info = $this->getMemberInfo(['member_erpid' => $result['dir_number']]);
            if(!$member_info) {
                // 不存在则加入系统
                $member = array();
                $member['member_erpid'] = $result['dir_number'];
                $member['member_password'] = md5(mt_rand());
                $member['member_mobile'] = $result['dir_phone'];
                $member['member_name'] = $result['dir_name'];
                $member['member_type'] = MEMBER_TYPE_1;
                $dir_member_id = $this->addMember($member);
                $member_info = $this->getMemberInfo(['member_id' => $dir_member_id]);
                $this->createErpInviter($member_info, [
                    'name' => $result['dir_name'],
                    'type' =>  $member['member_type'],
                    'phone' => $result['dir_phone'],
                ]);
            } else {
                // 存在则更新层级关系
                $dir_member_id = $member_info['member_id'];
            }

            // 更新上级
            $this->editMember(['member_id' => $member_id], [
                'inviter_id' => $dir_member_id,
            ]);

            if($member_info['member_type'] != MEMBER_TYPE_1) {
                // 更新等级
                $inviter_model->editInviter(['inviter_id' => $dir_member_id], [
                    'inviter_type' => MEMBER_TYPE_1
                ]);
                $member_info = $this->getMemberInfo(['member_id' => $dir_member_id]);
            }
        }
    }

    // 添加Inviter 数据
    public function createErpInviter($member_info, $erp_member_info) {
        // 注册分销商
        $inviter_data = array(
            'inviter_id' => $member_info['member_id'],
            'inviter_name' => $erp_member_info['name'],
            'inviter_type' => $erp_member_info['type'],
            'inviter_group' => MEMBER_AGENT_GROUP,
            'inviter_state' => 1,
            'inviter_contact_name' => $erp_member_info['name'],
            'inviter_contact_mobile' => $erp_member_info['phone'],
            'inviter_cityid' => 0,
            'inviter_provinceid' => 0,
            'inviter_areainfo' => '',
            'inviter_remark' => '',
            'inviter_areaid' => 0,
            'inviter_applytime' => time(),
        );

        Inviter::create($inviter_data);
    }

    /**
     * 会员详细信息（查库）
     * @access public
     * @author yunku
     * @param array $condition 条件
     * @param string $field 字段
     * @param bool $master 主服务器
     * @return array
     */
    public function getMemberInfo($condition, $field = '*', $master = false)
    {
        $res = db('member')->field($field)->where($condition)->master($master)->find();
        return $res;
    }

    /**
     * 取得会员详细信息（优先查询缓存）
     * 如果未找到，则缓存所有字段
     * @access public
     * @author yunku
     * @param int $member_id 会员ID
     * @return array
     */
    public function getMemberInfoByID($member_id)
    {
        $member_info = rcache($member_id, 'member');
        if (empty($member_info)) {
            $member_info = $this->getMemberInfo(array('member_id' => $member_id), '*', true);
            wcache($member_id, $member_info, 'member');
        }
        return $member_info;
    }

    /**
     * 会员列表
     * @access public
     * @author yunku
     * @param array $condition 条件
     * @param string $field    字段
     * @param number $page     分页
     * @param string $order    排序
     * @return array
     */
    public function getMemberList($condition = array(), $field = '*', $page = 0, $order = 'member_id desc')
    {
        if ($page) {
            $member_list = db('member')->where($condition)->order($order)->paginate($page,false,['query' => request()->param()]
            );
            $this->page_info = $member_list;
            return $member_list->items();
        }
        else {
            return db('member')->where($condition)->order($order)->select();
        }
    }

    /**
     * 会员数量
     * @access public
     * @author yunku
     * @param array $condition 查询条件
     * @return int
     */
    public function getMemberCount($condition)
    {
        return db('member')->where($condition)->count();
    }

    /**
     * 编辑会员
     * @access public
     * @author yunku
     * @param array $condition 检索条件
     * @param array $data 数据
     * @return bool
     */
    public function editMember($condition, $data)
    {
        $list = db('member')->where($condition)->select();
        $update = db('member')->where($condition)->update($data);
        if ($update && $list) {
            foreach ($list as $item) {
                dcache($item['member_id'], 'member');
            }
        }

        return $update;
    }

    /**
     * 直接保存更新
     */
    public function save($data = [], $where = [], $sequence = null)
    {
        if(isset($data['member_password'])) {
            if(!$data['member_password']) {
                unset($data['member_password']);
            } else {
                $data['member_password'] = md5(trim($data['member_password']));
            }
        }
        if(isset($data['member_paypwd'])) {
            if(!$data['member_paypwd']) {
                unset($data['member_paypwd']);
            }else{
                $data['member_paypwd'] = md5(trim($data['member_paypwd']));
            }
        }
        if(isset($this->member_id) && $this->member_id) {
            dcache($this->member_id, 'member');
        }
        return parent::save($data, $where, $sequence); // TODO: Change the autogenerated stub
    }

    /**
     * 登录时创建会话SESSION
     * @access public
     * @author yunku
     * @param type $member_info 会员信息
     * @param type $reg 规则
     * @return type
     */
    public function createSession($member_info = array(), $reg = false)
    {
        if (empty($member_info) || !is_array($member_info)) {
            return;
        }
        $member_gradeinfo = model('member')->getOneMemberGrade(intval($member_info['member_exppoints']));
        $member_info = array_merge($member_info, $member_gradeinfo);
        session('is_login', '1');
        session('member_id', $member_info['member_id']);
        session('member_name', $member_info['member_name']);
        session('member_email', $member_info['member_email']);
        session('is_buy', isset($member_info['is_buylimit']) ? $member_info['is_buylimit'] : 1);
        session('avatar', $member_info['member_avatar']);
        session('level', isset($member_info['level']) ? $member_info['level'] : '');
        session('level_name', isset($member_info['level_name']) ? $member_info['level_name'] : '');
        session('member_exppoints', $member_info['member_exppoints']);  //经验值
        session('member_points', $member_info['member_points']);        //积分值
        // 头衔COOKIE
        $this->set_avatar_cookie();

        if (trim($member_info['member_qqopenid'])) {
            session('openid', $member_info['member_qqopenid']);
        }
        if (trim($member_info['member_sinaopenid'])) {
            session('slast_key.uid', $member_info['member_sinaopenid']);
        }
        if (trim($member_info['member_wxopenid'])) {
            session('wxopenid', $member_info['member_wxopenid']);
        }
        if (trim($member_info['member_wxunionid'])) {
            session('wxunionid', $member_info['member_wxunionid']);
        }

        if (!$reg) {
            //添加会员积分
            $this->addPoint($member_info);
            //添加会员经验值
            $this->addExppoint($member_info);
        }

        if (!empty($member_info['member_logintime'])) {
            $update_info = array(
                'member_loginnum' => ($member_info['member_loginnum'] + 1),
                'member_logintime' => TIMESTAMP,
                'member_old_logintime' => $member_info['member_logintime'],
                'member_login_ip' => request()->ip(),
                'member_old_login_ip' => $member_info['member_login_ip']
            );
            $this->editMember(array('member_id' => $member_info['member_id']), $update_info);
        }
        cookie('cart_goods_num', '', -3600);
        // cookie中的cart存入数据库
        model('cart')->mergeCart($member_info);
        // cookie中的浏览记录存入数据库
        model('goodsbrowse')->mergeGoodsbrowse(session('member_id'));

        if (isset($member_info['auto_login']) && ($member_info['auto_login'] == 1)) {
            $this->auto_login();
        }
    }


    /**
     * 7天内自动登录
     * @access public
     * @author yunku
     */
    public function auto_login()
    {
        // 自动登录标记 保存7天
        cookie('auto_login', sc_encrypt(session('member_id'), MD5_KEY), 7 * 24 * 60 * 60);
    }

    /**
     * 设置cookie
     * @access public
     * @author yunku
     */
    public function set_avatar_cookie()
    {
        cookie('member_avatar', session('avatar'), 365 * 24 * 60 * 60);
    }

    /**
     * 获取会员信息
     * @access public
     * @author yunku
     * @param    array $condition 会员条件
     * @param    string $field 显示字段
     * @return    array 数组格式的返回结果
     */
    public function infoMember($condition, $field = '*')
    {
        if (empty($condition))
            return false;
        $member_info = db('member')->where($condition)->field($field)->find();
        return $member_info;
    }

    /**
     * 注册
     * @access public
     * @author yunku
     * @param type $register_info
     * @return type
     */
    public function register($register_info)
    {
        // 验证用户名是否重复
        $check_member_name = $this->getMemberInfo(array('member_name' => $register_info['member_name']));
        if (is_array($check_member_name) and count($check_member_name) > 0) {
            return array('error' => '用户名已存在');
        }

        // 会员添加
        $member_info = array();
        $member_info['member_name'] = $register_info['member_name'];
        $member_info['member_password'] = $register_info['member_password'];
        //会员邮箱
        if (isset($register_info['member_email'])){
            $member_info['member_email'] = $register_info['member_email'];
        }
        //添加邀请人(推荐人)会员积分
        isset($register_info['inviter_id']) && $member_info['inviter_id'] = $register_info['inviter_id'];

        if (isset($register_info['member_mobilebind'])) {
            $member_info['member_mobilebind'] = $register_info['member_mobilebind'];
            $member_info['member_mobile'] = $register_info['member_mobile'];
        }
        $insert_id = $this->addMember($member_info);
        if ($insert_id) {
            $this->addMemberAfter($insert_id,$member_info);
            $member_info = db('member')->where('member_id', $insert_id)->find();
            return $member_info;
        }
        else {
            return array('error' => '注册失败');
        }
    }

    /**
     * 新增用户后,赠送积分,添加相册等其他操作,主要是针对于 新增用户注册获得积分，等奖励信息的处理
     * @access public
     * @author yunku
     * @param type $member_id 会员ID
     * @param type $member_info 会员信息
     * @return type
     */
    public function addMemberAfter($member_id,$member_info){
        //添加会员积分
        if (config('points_isuse')) {
            model('points')->savePointslog('regist', array('pl_memberid' => $member_id, 'pl_membername' => $member_info['member_name']), false);

            $member_model = new Member();
            $member_info = $member_model->getMemberInfoByID($member_id);
            if (isset($member_info['inviter_id'])) {
                $inviter = $member_model->getMemberInfoByID($member_info['inviter_id']);
                // 会员组
                if(!$inviter){
                    $inviter['member_group'] = 1;
                }
                $member_model->editMember(['member_id' => $member_id], ['member_group' => $inviter['member_group']]);
                // 门店会员统计
                db('inviter')->where('inviter_id='.$member_info['store_id'])->setInc('inviter_1_quantity');

                //添加邀请人(推荐人)会员积分
                $inviter_name = sc_getvalue_byname('member', 'member_id', $member_info['inviter_id'], 'member_name');
                if($inviter_name){
                    model('points')->savePointslog('inviter', array(
                        'pl_memberid' => $member_info['inviter_id'], 'pl_membername' => $inviter_name,
                        'invited' => $member_info['member_name']
                    ));
                }

            }
        }
    }

    /**
     * 注册商城会员
     * @access public
     * @author yunku
     * @param  array $data 会员信息
     * @return array 数组格式的返回结果
     */
    public function addMember($data)
    {
        if (empty($data)) {
            return false;
        }
        try {
            $this->startTrans();
            $member_info = array();

            $member_info['member_review'] = $data['member_review'];
            $member_info['member_state'] = $data['member_state'];

            // 归属默认门店
            if(!isset($data['inviter_id']) || !$data['inviter_id']) {
                $data['inviter_id'] = DEFAULT_STORE;
            }

            $inviter = Member::get($data['inviter_id']);
            $data['store_id'] = $inviter['inviter_id'];     // 门店即邀请人

            # 万嘉的 member_type => 会员级别
            if (isset($data['member_group'])) {
                $member_info['member_type']  = isset($data['member_type']) ? $data['member_type'] : MEMBER_GROUP_LEVEL_1;    // 1级或2级
                $member_info['member_group'] = isset($data['member_group']) ? $data['member_group'] : MEMBER_CUSTOMER_GROUP; // 代理商 万嘉 1批发商或9普通会员
            } else {
                $member_info['member_type']  = MEMBER_GROUP_LEVEL_1;
                $member_info['member_group'] = MEMBER_CUSTOMER_GROUP;   // 普通用户
            }

            $member_info['member_name'] = $data['member_name'];
            $member_info['member_password'] = md5(trim($data['member_password']));
            if (isset($data['member_email'])) {
                $member_info['member_email'] = $data['member_email'];
            }

            isset($data['member_erpid']) and $member_info['member_erpid'] = $data['member_erpid'];
            isset($data['member_erpinfo']) and $member_info['member_erpinfo'] = $data['member_erpinfo'];

            $member_info['inviter_id'] = $data['inviter_id'];
            $member_info['store_id'] = $data['store_id'];
            $member_info['member_addtime'] = TIMESTAMP;
            $member_info['member_logintime'] = TIMESTAMP;
            $member_info['member_old_logintime'] = TIMESTAMP;
            $member_info['member_login_ip'] = request()->ip();
            $member_info['member_old_login_ip'] = $member_info['member_login_ip'];

            isset($data['member_truename']) and $member_info['member_truename'] = $data['member_truename'];
            isset($data['member_qq']) and $member_info['member_qq'] = $data['member_qq'];
            isset($data['member_sex']) and $member_info['member_sex'] = $data['member_sex'];
            isset($data['member_avatar']) and $member_info['member_avatar'] = $data['member_avatar'];
            isset($data['member_qqopenid']) and $member_info['member_qqopenid'] = $data['member_qqopenid'];
            isset($data['member_qqinfo']) and $member_info['member_qqinfo'] = $data['member_qqinfo'];
            isset($data['member_sinaopenid']) and $member_info['member_sinaopenid'] = $data['member_sinaopenid'];
            isset($data['member_sinainfo']) and $member_info['member_sinainfo'] = $data['member_sinainfo'];
            //添加邀请人(推荐人)会员积分
            isset($data['inviter_id']) and $member_info['inviter_id'] = $data['inviter_id'];

            //  手机注册登录绑定
            if (isset($data['member_mobilebind'])) {
                $member_info['member_mobile'] = $data['member_mobile'];
                $member_info['member_mobilebind'] = $data['member_mobilebind'];
            }
            if (isset($data['member_wxunionid'])) {
                $member_info['member_wxunionid'] = $data['member_wxunionid'];
                $member_info['member_wxinfo'] = $data['member_wxinfo'];
                $member_info['member_wxopenid'] = $data['member_wxopenid'];
            }
            $insert_id = db('member')->insertGetId($member_info);
            if (!$insert_id) {
                exception();
            }
            $insert = $this->addMemberCommon(array('member_id' => $insert_id));
            if (!$insert) {
                exception();
            }

            //添加会员积分
            if (config('points_isuse')) {
                model('points')->savePointslog('regist', array(
                    'pl_memberid' => $insert_id, 'pl_membername' => $data['member_name']
                ), false);
            }
            $this->commit();
            return $insert_id;
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
    }

    /**
     * 会员登录检查
     * @access public
     * @author yunku
     * @return bool
     */
    public function checkloginMember()
    {
        if (session('is_login') == '1') {
            @header("Location: " . url('Home/Member/index'));
            exit();
        }
    }

    /**
     * 检查会员是否允许举报商品
     * @access public
     * @author yunku
     * @param type $member_id 会员id
     * @return boolean
     */
    public function isMemberAllowInform($member_id)
    {
        $condition = array();
        $condition['member_id'] = $member_id;
        $member_info = $this->getMemberInfo($condition, 'inform_allow');
        if (intval($member_info['inform_allow']) === 1) {
            return true;
        }
        else {
            return false;
        }
    }

    /**
     * 取单条信息
     * @access public
     * @author yunku
     * @param type $condition 条件
     * @param type $fields 字段
     * @return type
     */
    public function getMemberCommonInfo($condition = array(), $fields = '*')
    {
        return db('membercommon')->where($condition)->field($fields)->find();
    }

    /**
     * 插入扩展表信息
     * @access public
     * @author yunku
     * @param type $data 数据
     * @return bool
     */
    public function addMemberCommon($data)
    {
        return db('membercommon')->insert($data);
    }

    /**
     * 编辑会员扩展表
     * @access public
     * @author yunku
     * @param array $data
     * @param array $condition
     * @return Ambigous <mixed, boolean, number, unknown, resource>
     */
    public function editMemberCommon($data, $condition)
    {
        return db('membercommon')->where($condition)->update($data);
    }

    /**
     * 添加会员积分
     * @access public
     * @author yunku
     * @param type $member_info 会员信息
     * @return type
     */
    public function addPoint($member_info)
    {
        if (!config('points_isuse') || empty($member_info))
            return;

        //一天内只有第一次登录赠送积分
        if (trim(@date('Y-m-d', $member_info['member_logintime'])) == trim(date('Y-m-d')))
            return;

        //加入队列
        $queue_content = array();
        $queue_content['member_id'] = $member_info['member_id'];
        $queue_content['member_name'] = $member_info['member_name'];
        \mall\queue\QueueClient::push('addPoint', $queue_content);
    }

    /**
     * 添加会员经验值
     * @access public
     * @author yunku
     * @param unknown $member_info 会员信息
     */
    public function addExppoint($member_info)
    {
        if (empty($member_info))
            return;

        //一天内只有第一次登录赠送经验值
        if (trim(@date('Y-m-d', $member_info['member_logintime'])) == trim(date('Y-m-d')))
            return;

        //加入队列
        $queue_content = array();
        $queue_content['member_id'] = $member_info['member_id'];
        $queue_content['member_name'] = $member_info['member_name'];
        \mall\queue\QueueClient::push('addExppoint', $queue_content);
    }

    /**
     * 取得会员安全级别
     * @access public
     * @author yunku
     * @param array $member_info 会员信息
     */
    public function getMemberSecurityLevel($member_info = array())
    {
        $tmp_level = 0;
        if ($member_info['member_emailbind'] == '1') {
            $tmp_level += 1;
        }
        if ($member_info['member_mobilebind'] == '1') {
            $tmp_level += 1;
        }
        if ($member_info['member_paypwd'] != '') {
            $tmp_level += 1;
        }
        return $tmp_level;
    }

    /**
     * 获得会员等级
     * @access public
     * @author yunku
     * @param bool $show_progress 是否计算其当前等级进度
     * @param int $exppoints 会员经验值
     * @param array $cur_level 会员当前等级
     * @return type
     */
    public function getMemberGradeArr($show_progress = false, $exppoints = 0, $cur_level = '')
    {
        $member_grade = config('member_grade') ? unserialize(config('member_grade')) : array();

        //处理会员等级进度
        if ($member_grade && $show_progress) {
            $is_max = false;
            if ($cur_level === '') {
                $cur_gradearr = $this->getOneMemberGrade($exppoints, false, $member_grade);
                $cur_level = $cur_gradearr['level'];
            }
            foreach ($member_grade as $k => $v) {
                if ($cur_level == $v['level']) {
                    $v['is_cur'] = true;
                }
                $member_grade[$k] = $v;
            }
        }
        return $member_grade;
    }
    /**
     * 会员管理页面的会员等级筛选
     */
    public function getMemberGroupArr($group_type = false)
    {
        $member_group_level = MemberGroup::$member_level;
        $member_group_arr   = MemberGroup::$member_group;
        $list  = [];
        for ($i=1; $i<=2; $i++) {
            $member_group = $i == MEMBER_AGENT_GROUP ? MEMBER_AGENT_GROUP : MEMBER_CUSTOMER_GROUP; // 1=>批发商 9=>普通会员
            $key1         = $member_group . 1;       // 组级别
            $level1       = $member_group . '_' . 1; // 组_级别 1_1一级批发商 9_2二级普通会员
            $list[$key1] = [
                'level'      => $level1,
                'level_name' => $member_group_level[1] . $member_group_arr[$member_group], // 级别组名
                'selected'   => '',
            ];
            $key2 = $member_group . 2;
            $level2 = $member_group . '_' . 2;
            $list[$key2] = [
                'level'      => $level2,
                'level_name' => $member_group_level[2] . $member_group_arr[$member_group],
                'selected'   => '',
            ];
        }
        if ($group_type) {
            if (isset($list[$group_type])) {
                $list[$group_type]['selected'] = 'selected';
            } else {
                end($list);
                $end_key = key($list);
                $list[$end_key]['selected'] = 'selected'; // 最后一个元素设置为选中
            }
        }
        return $list;
    }


    /**
     * 获得某一会员等级
     * @access public
     * @author yunku
     * @param int $exppoints 会员经验值
     * @param bool $show_progress 是否计算其当前等级进度
     * @param array $member_grade 会员等级
     * @return type
     */
    public function getOneMemberGrade($exppoints, $show_progress = false, $member_grade = array())
    {
        if (!$member_grade) {
            $member_grade = config('member_grade') ? unserialize(config('member_grade')) : array();
        }
        if (empty($member_grade)) {//如果会员等级设置为空
            $grade_arr['level'] = -1;
            $grade_arr['level_name'] = '暂无等级';
            return $grade_arr;
        }

        $exppoints = intval($exppoints);

        $grade_arr = array();
        if ($member_grade) {
            foreach ($member_grade as $k => $v) {
                if ($exppoints >= $v['exppoints']) {
                    $grade_arr = $v;
                }
            }
        }
        //计算提升进度
        if ($show_progress == true) {
            if (intval($grade_arr['level']) >= (count($member_grade) - 1)) {//如果已达到顶级会员
                $grade_arr['downgrade'] = $grade_arr['level'] - 1; //下一级会员等级
                $grade_arr['downgrade_name'] = $member_grade[$grade_arr['downgrade']]['level_name'];
                $grade_arr['downgrade_exppoints'] = $member_grade[$grade_arr['downgrade']]['exppoints'];
                $grade_arr['upgrade'] = $grade_arr['level']; //上一级会员等级
                $grade_arr['upgrade_name'] = $member_grade[$grade_arr['upgrade']]['level_name'];
                $grade_arr['upgrade_exppoints'] = $member_grade[$grade_arr['upgrade']]['exppoints'];
                $grade_arr['less_exppoints'] = 0;
                $grade_arr['exppoints_rate'] = 100;
            }
            else {
                $grade_arr['downgrade'] = $grade_arr['level']; //下一级会员等级
                $grade_arr['downgrade_name'] = $member_grade[$grade_arr['downgrade']]['level_name'];
                $grade_arr['downgrade_exppoints'] = $member_grade[$grade_arr['downgrade']]['exppoints'];
                $grade_arr['upgrade'] = $member_grade[$grade_arr['level'] + 1]['level']; //上一级会员等级
                $grade_arr['upgrade_name'] = $member_grade[$grade_arr['upgrade']]['level_name'];
                $grade_arr['upgrade_exppoints'] = $member_grade[$grade_arr['upgrade']]['exppoints'];
                $grade_arr['less_exppoints'] = $grade_arr['upgrade_exppoints'] - $exppoints;
                $grade_arr['exppoints_rate'] = round(($exppoints - $member_grade[$grade_arr['level']]['exppoints']) / ($grade_arr['upgrade_exppoints'] - $member_grade[$grade_arr['level']]['exppoints']) * 100, 2);
            }
        }
        return $grade_arr;
    }

    /**
     * 获得某一级会员等级
     */
    public function getOneMemberGroup($member_group, $member_type, $field = false)
    {
        $return_str = '';
        if (in_array($member_type, [MEMBER_GROUP_LEVEL_1, MEMBER_GROUP_LEVEL_2])) {
            $return_str .= (MemberGroup::$member_level)[$member_type];
        }
        if (in_array($member_group, [MEMBER_AGENT_GROUP, MEMBER_CUSTOMER_GROUP])) {
            $return_str .= (MemberGroup::$member_group)[$member_group];
        }
        return $return_str;
    }

    /**
     * 登录生成token
     * @access public
     * @author yunku
     * @param type $member_id 会员id
     * @param type $member_name 会员名字
     * @param type $client 客户端
     * @return type
     */
    public function getBuyerToken($member_id, $member_name, $client,$openid='') {
        $mbusertoken_model = model('mbusertoken');
        //重新登录后以前的令牌失效
        //暂时停用
        //$condition = array();
        //$condition['member_id'] = $member_id;
        //$condition['member_clienttype'] = $client;
        //$mbusertoken_model->delMbusertoken($condition);
        //生成新的token
        $mb_user_token_info = array();
        $token = md5($member_name . strval(TIMESTAMP) . strval(rand(0, 999999)));
        $mb_user_token_info['member_id'] = $member_id;
        $mb_user_token_info['member_name'] = $member_name;
        $mb_user_token_info['member_token'] = $token;
        $mb_user_token_info['member_logintime'] = TIMESTAMP;
        $mb_user_token_info['member_clienttype'] = $client;
        if(!empty($openid)){
            $mb_user_token_info['member_openid'] = $openid;
        }

        $result = $mbusertoken_model->addMbusertoken($mb_user_token_info);
        if ($result) {
            return $token;
        } else {
            return null;
        }
    }

    /**
     * 获取分享人信息
     */
    public static function parentInviter($member) {
        is_numeric($member) and $member = Member::get($member);
        if($member['member_type'] == MEMBER_TYPE_1) return;

        // 直接分享
        if($member['inviter_id'] || $member['member_type'] == 3) {
            return Member::get($member['inviter_id']);
        }

        // 默认区域
        $inviter = Inviter::get($member['member_id']);
        $area = Area::get($inviter['inviter_areaid']);

        if($area['member_id'] > 0) {
            $member_id = $area['member_id'];
        } else {
            // 默认
            $member_id = DEFAULT_AGENT;
        }
        return Member::get($member_id);
    }

    // 获取分享人名称
    public static function parentInviterName($member) {
        $patent_inviter = static::parentInviter($member);
        return $patent_inviter ? ($patent_inviter['member_name']) : '';
    }

    // 成员数量
    public static function totalMember($inviter) {
        is_numeric($inviter) and $inviter = Inviter::get($inviter);

        if($inviter['inviter_type'] == MEMBER_TYPE_1) {
            // 区域
            $area_member_id = $inviter['inviter_id'] == DEFAULT_AGENT ? 0 : $inviter['inviter_id'];
            return Member::where('inviter_id', $inviter['inviter_id'])
                ->whereOr('member_type = '.MEMBER_TYPE_2.' and inviter_id = 0 and member_areaid in ('.Db::name('area')->where([
                        'member_id' => $area_member_id,
                        'area_deep' => 3,
                    ])->field('area_id')->buildSql().')')
                ->count();
        } else {
            return Member::where([
                'store_id' => $inviter['inviter_id'],
                'member_type' => MEMBER_TYPE_3,
            ])->count();
        }
    }
}
